package com.twittex.model
{
	import com.adobe.serialization.json.JSON;
	import com.arc90.rpc.events.FaultEvent;
	import com.arc90.rpc.events.ResultEvent;
	import com.arc90.rpc.rest.RESTService;
	import com.arc90.rpc.rest.RESTServiceMethod;
	import com.twittex.TwittexFacade;
	import com.twittex.model.vo.LoginVO;
	import com.twittex.model.vo.UserVO;
	
	import flash.net.SharedObject;
	
	import org.puremvc.as3.patterns.proxy.Proxy;

	public class LoginProxy extends Proxy
	{
		public static const NAME:String = "LoginProxy";

		private static const TWITTER_VERIFY_CREDENTIALS:String = "http://twitter.com/account/verify_credentials.json";
		private static const SESSION_SHARED_OBJECT:String = "session";
		
		private var savedData:SharedObject;
		
		public function LoginProxy(proxyName:String=null, data:Object=null)
		{
			super(NAME, data);
			restoreData();
		}

		public function get loginVO():LoginVO {
			return data as LoginVO;
		}
		
		public function login(tryLogin:LoginVO):void {
			var service:RESTService = new RESTService();

			service.setCredentials(tryLogin.login, tryLogin.password);
			service.url = TWITTER_VERIFY_CREDENTIALS;
			service.method = RESTServiceMethod.GET;
			service.resultFormat = RESTService.RESULT_FORMAT_TEXT;
			
			if(tryLogin.remember) {
				saveData(tryLogin);
			}
				
			var successHandler:Function = function (event:ResultEvent):void {
				var rawData:String = String(event.result);
				var user:UserVO = new UserVO(JSON.decode(rawData));

				setData(tryLogin);
				sendNotification(TwittexFacade.LOGIN_SUCCEED, user);
			}
			
			var failHandler:Function = function (event:FaultEvent):void {
				sendNotification(TwittexFacade.LOGIN_FAILED);
			}

			service.addEventListener(ResultEvent.RESULT, successHandler);
			service.addEventListener(FaultEvent.FAULT, failHandler);
			service.send();
		}
		
		private function restoreData():void {
			var data:LoginVO = new LoginVO();
			
			savedData = SharedObject.getLocal(SESSION_SHARED_OBJECT);
			
			data.login = savedData.data.login;
			data.password = savedData.data.password;
			data.remember = savedData.data.remember;
			setData(data);
		}
		
		private function saveData(data:LoginVO):void {
			savedData = SharedObject.getLocal(SESSION_SHARED_OBJECT);

			savedData.data.login = data.login;
			savedData.data.password = data.password;
			savedData.data.remember = data.remember;
			savedData.flush();
		}
	}
}